﻿namespace TouchFish.SingletonClass
{
    public interface ISingleton
    {
        void OnSingletonInit();
    }

    public class Singleton<T> where T : ISingleton, new()
    {
        private static T _instance;
        private static readonly object Locker = new object();

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (Locker)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                            _instance.OnSingletonInit();
                        }
                    }
                }
                return _instance;
            }
        }
    }

    public static class Singleton
    {
        private static object _locker = new object();

        public static T GetInstance<T>() where T : class, ISingleton, new()
        {
            if (InstanceStorage<T>.Instance == null)
            {
                lock (_locker)
                {
                    if (InstanceStorage<T>.Instance == null)
                    {
                        InstanceStorage<T>.Instance = new T();
                        InstanceStorage<T>.Instance.OnSingletonInit();
                    }
                }
            }
            return InstanceStorage<T>.Instance;
        }

        private static class InstanceStorage<T> where T : class, new()
        {
            internal static volatile T Instance = default(T);
        }
    }
}